package com.jiangcheng.demo.service.impl;

import com.jiangcheng.demo.entity.Reply;
import com.jiangcheng.demo.mapper.ReplyMapper;
import com.jiangcheng.demo.service.LikedService;
import com.jiangcheng.demo.service.ReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangcheng.demo.utils.FindReplysVo;
import com.jiangcheng.demo.utils.FindReplytoReplyByCommentId;
import com.jiangcheng.demo.utils.LikedVo;
import com.jiangcheng.demo.utils.NewResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-07-26
 */
@Service
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply> implements ReplyService {
    @Resource
    ReplyMapper replyMapper;
    @Autowired
    LikedService likedService;

    @Override
    public int findReplyCountByCommentId(int commentId) {
        int count = replyMapper.findCountByCommentId(commentId);

        return count;
    }

    @Override
    public NewResult findReplyByCommentId(int commentId,int uId) {
        List<Object> list = new ArrayList<Object>();
        // 第一次查询回复 第二次查询回复的回复
        List<FindReplysVo> findReplysVos = replyMapper.findAllReplyByCommentId(commentId);
        for (FindReplysVo findReplysVo: findReplysVos){
            LikedVo likeInfo = getLikeInfo(findReplysVo.getRId(), uId);
            findReplysVo.setLikeNum(likeInfo.getCount());
            findReplysVo.setIsLike(likeInfo.getExists());
            list.add(findReplysVo);
        }
        // 查询回复的回复
        List<FindReplytoReplyByCommentId> replyToReplys = replyMapper.findAllReplytoRepleByCommentId(commentId);
        for (FindReplytoReplyByCommentId replyToReply: replyToReplys){
            LikedVo likeInfo = getLikeInfo(replyToReply.getReplyReplyId(), uId);
            replyToReply.setLikeNum(likeInfo.getCount());
            replyToReply.setIsLike(likeInfo.getExists());
            list.add(replyToReply);
        }

        return new NewResult(200,true,"查询回复成功", list);
    }
    // 填充点赞信息
    public LikedVo getLikeInfo(int rid,int uId){
        LikedVo likeNumByObjId = likedService.findLikeNumByObjId(rid, 3, uId);
        return likeNumByObjId;
    }


    @Override
    public NewResult insertReply(Reply reply) {
        int insert = replyMapper.insert(reply);
        if (insert < 1 ){
            return new NewResult(400,false, "网络异常");
        }
        return new NewResult(200,true, "回复成功");
    }
}
